using System;
using System.Timers;

namespace ebcpatterns.concurrent
{
    public class Throttle<T> : IThrottle<T>
    {
        private readonly int periodInMilliseconds;
        private Timer timer;
        private T message;

        public Throttle()
            : this(5000) {
        }

        public Throttle(int periodInMilliseconds) {
            this.periodInMilliseconds = periodInMilliseconds;
        }

        public void Process(T t) {
            message = t;
            if (timer == null) {
                timer = new Timer {
                    Interval = periodInMilliseconds
                };
                timer.Elapsed +=
                    delegate {
                        timer.Dispose();
                        timer = null;
                        Result(message);
                    };
                timer.Start();
            }
            else {
                timer.Stop();
                timer.Start();
            }
        }

        public event Action<T> Result;
    }
}